const bt1 = $("#bt1");
const bt2 = $("#bt2");
const bt3 = $("#bt3");
const bt4 = $("#bt4");

$(function() {
    // set global header
    const token = localStorage.getItem('token');
    // check
    if (token !== null && token !== '') {
        $.ajaxSetup({
            headers: {
                "token": token,
                "Content-Type": "application/json"
            }
        });
    } else { // if not login, redirect
        tips('未登录，将跳转');
        $.ajaxSetup({
            beforeSend: () => {
                ajax.abort();
            }
        });
        setTimeout(() => {
            location.href = "/login";
        }, 3000);
    }
    // flush data
    bt1.trigger('click');
});

$("#logout").click(() => {
    localStorage.removeItem('token');
    location.href = "/login";
});

$("#svg").click(() => {
    $("#some").slideToggle(500);
});

bt1.click(() => {
    setActive(bt1, $("main table:first"));
    $("#tb1only").show();
    $("#tb1all").show();
    $("#tb1search").show();
    doAjaxAndAttachData('/register', $("#tb1"), () => {
        // attach btn & event
        let td = $('<td></td>');
        let btn = $('<button class="e_btn">编辑</button>');
        let btn2 = $('<button class="e_btn">删除</button>');
        td.append(btn, btn2);
        $("#tb1 tr").last().append(td);
        btn.click(() => {
            let pid = btn.parent().parent().children().html(); // 事件中需重新获取
            let panel = $(".edit_register");
            panel.attr('id', 'r_' + pid);
            panel.slideDown(300);
        });
        btn2.click(() => {
            $("#confirm").slideDown(300);
            // delete
            $("#d_submit").click(() => {
                let pid = btn2.parent().parent().children().html();
                $.ajax({
                    type: 'DELETE',
                    url: '/register/' + pid,
                    dataType: 'JSON',
                    success: (data) => {
                        if (data.code === 1) tips('删除成功');
                        else tips(data.msg);
                        flushData();
                    },
                    error: (xhr, err, errorThrown) => {
                        tips('[ERROR] DELETE ' + xhr.statusText + errorThrown);
                    }
                });
                $("#confirm").slideUp(300);
            });

        });
    });
});


bt2.click(() => {
    setActive(bt2, $("main table:eq(1)"));
    $("#tb2all").show();
    doAjaxAndAttachData('/schedule', $("#tb2"), () => {
        $("#tb2 tr").last().append(jqBtnFactory($(".edit_schedule"), 's_'));
    });
});


bt3.click(() => {
    setActive(bt3, $("main table:eq(2)"));
    doAjaxAndAttachData('/salary', $("#tb3"), () => {
        $("#tb3 tr").last().append(jqBtnFactory($(".edit_salary"), 'c_'));
    });
});

bt4.click(() => {
    setActive(bt4, $("main table:eq(3)"));
    doAjaxAndAttachData('/charge', $("#tb4"), () => {
        $("#tb4 tr").last().append(jqBtnFactory($(".edit_charge"), 'sa_'));
    });
});

// param: msg
// desc: drop down tip panel
function tips(tip) {
    const panel = $("#tips");
    panel.html(tip);
    panel.slideDown(300);
    setTimeout(() => {
        panel.slideUp(300);
    }, 3000);
}

// param: panel-> attach to
//        id-> btn id
// desc:  create button ,set attr and attach to indicated node
// ret:   btn encapsulated in td
function jqBtnFactory(panel, id) {
    let td = $('<td></td>');
    let btn = $('<button class="e_btn">编辑</button>');
    td.append(btn);
    btn.click(() => {
        let pid = btn.parent().parent().children().html();
        panel.attr('id', id + pid);
        panel.slideDown(300);
    });
    return td;
}

// param: url-> jquery ajax url
//        el-> attach to
//        func-> custom function for describe attach table data method
// desc:  send get ajax request , attach response data to indicated element 
function doAjaxAndAttachData(url, el, func) {
    $.ajax({
        type: 'GET', url: url, dataType: 'JSON',
        success: function(data) {
            if (data.code === 1) addDataToTable(el, data.data, func);
            else tips(data.msg);
        },
        error: (xhr) => {
            tips('[ERROR] LOAD ' + xhr.statusText);
        }
    });
}

// param: 
// desc:  add data into table
function addDataToTable(tbody, data, func) {
    tbody.html('');
    let th = '';
    data.forEach(e => {
        let el = $('<tr></tr>');
        for (const key in e) {
            if (Object.hasOwnProperty.call(e, key)) {
                if (e.gender === 1 || e.gender === 2) {
                    //replace gender
                    e.gender = e.gender === 1 ? '男' : '女';
                }
                const element = e[key];
                th += '<td>' + element + '</td>';
            }
        }
        // append element
        el.html(th);
        tbody.append(el);
        // add button
        if (func !== '')
            func();
        th = '';
    });
}

// param: 
// ret:   
// desc:   
function doPutAjax(panel, getData, url) {
    panel.slideUp(300);
    let pid = panel.attr('id').replace(/\D/g, '');
    const data = JSON.stringify(getData());
    $.ajax({
        type: 'PUT',
        url: url + pid,
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        data: data,
        success: (data) => {
            if (data.code === 1) tips('修改成功');
            else tips(data.msg);
            // flush
            flushData();
        },
        error: (xhr, err, errorThrown) => {
            tips('[ERROR] MODIFY ' + xhr.statusText + errorThrown);
        }
    });
}

// flush data
function flushData() {
    $(".asideActive").trigger('click');
}


// set the visibility of tables
function setActive(el, table) {
    $("#mySidenav").find("a").removeClass("asideActive");
    $("table").removeClass("active");
    table.addClass("active");
    el.addClass("asideActive");
    $("#tbTitle").html(el.html());
    $("#tb1only").hide();
    $("#tb1all").hide();
    $("#tb2all").hide();
    $("#tb1search").hide();
}


// panel of add register
$("#tb1only").click(() => {
    $(".bgc").slideDown(300);
});

$("#ar_cancel").click(() => {
    $(".bgc").slideUp(300);
});

$("#ar_submit").click(() => {
    $(".bgc").slideUp(300);
    const data = JSON.stringify(addRegister());
    // send data
    $.ajax({
        type: 'POST',
        url: '/register',
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        data: data,
        success: (data) => {
            if (data.code === 1) tips('添加成功');
            else tips(data.msg);
            // flush
            flushData();
        },
        error: (xhr, err, errorThrown) => {
            tips('[ERROR] INSERT ' + xhr.statusText + errorThrown);
        }
    });
});

// search panel
$("#tb1search").click(() => {
    $(".search").slideDown(300);
});
$("#sh_submit").click(() => {
    const data = JSON.stringify(searchRegister());
    $.ajax({
        type: 'POST',
        url: '/register/search',
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        data: data,
        success: (data) => {
            if (data.code === 1) addDataToTable($("#result_panel"), data.data, '');
            else tips(data.msg);
        },
        error: (xhr, err, errorThrown) => {
            tips('[ERROR] SEARCH ' + xhr.statusText + errorThrown);
        }
    });
});
$("#sh_cancel").click(() => {
    $(".search").slideUp(300);
});

$("#d_cancel").click(() => {
    $("#confirm").slideUp(300);
});

// modify register
$("#mr_submit").click(() => {
    doPutAjax($(".edit_register"), updateRegister, '/register/');
});
$("#mr_cancel").click(() => {
    $(".edit_register").slideUp(300);
});

// modify schedule
$("#s_submit").click(() => {
    doPutAjax($(".edit_schedule"), updateSche, '/schedule/');
});
$("#s_cancel").click(() => {
    $(".edit_schedule").slideUp(300);
});

// modify salary
$("#sa_submit").click(() => {
    doPutAjax($(".edit_salary"), updateSalary, '/salary/');
});

$("#sa_cancel").click(() => {
    $(".edit_salary").slideUp(300);
});

// modify charge
$("#c_submit").click(() => {
    doPutAjax($(".edit_charge"), updateCharge, '/charge/');
});

$("#c_cancel").click(() => {
    $(".edit_charge").slideUp(300);
});

// Statistics
$("#tb1all").click(() => {
    // load data
    $.ajax({
        type: 'GET',
        url: '/register/count',
        dataType: 'JSON',
        success: (data) => {
            if (data.code !== 1) tips(data.msg);
            else if (data.code === 1) {
                // add data
                let tbody = $("#count_panel");
                tbody.html('');
                let th = '';
                data.data.forEach(e => {
                    let el = $('<tr></tr>');
                    for (const key in e) {
                        if (Object.hasOwnProperty.call(e, key)) {
                            const element = e[key];
                            th += '<td>' + element + '</td>';
                        }
                    }
                    // append element
                    el.html(th);
                    tbody.append(el);
                    th = '';
                });
            }
        },
        error: () => {
            tips('[ERROR] GET request');
        }
    });
    $("#count_p").slideDown(300);

});
$("#count_btn").click(() => {
    $("#count_p").slideUp(300);
});

// details
// add data to db
function addRegister() {
    let data = {
        "pid": $("#ar_pid").val(),
        "name": $("#ar_name").val(),
        "gender": $("input[name='sex']:checked").next("span").text() === '女' ? '2' : '1',
        "age": $("#ar_age").val(),
        "subj": $("#ar_subj").val(),
        "addr": $("#ar_addr").val(),
        "phone": $("#ar_phone").val(),
        "profession": $("#ar_profession").val()
    };
    setTimeout(() => {
        $("input").val('');
    }, 500);
    return data;
}

// search register data
function searchRegister() {
    let data = {
        "pid": $("#sh_pid").val(),
        "name": $("#sh_name").val(),
        "subj": $("#sh_subj").val(),
        "profession": $("#sh_profession").val()
    };
    return data;
}

// update register data
function updateRegister() {
    let data = {
        "name": $("#mr_name").val(),
        "gender": $("input[name='gender']:checked").next("span").text() === '女' ? '2' : '1',
        "age": $("#mr_age").val(),
        "subj": $("#mr_subj").val(),
        "addr": $("#mr_addr").val(),
        "phone": $("#mr_phone").val(),
        "profession": $("#mr_profession").val()
    };
    setTimeout(() => {
        $("input").val('');
    }, 500);
    return data;
}

// update schedule data
function updateSche() {
    let data = {
        "startTime": $("#s_start").val(),
        "overTime": $("#s_end").val()
    };
    setTimeout(() => {
        $("#s_start").val('');
        $("#s_end").val('');
    }, 500);
    return data;
}

// update charge data
function updateCharge() {
    let data = {
        "charge": $("#c_charge").val()
    };
    setTimeout(() => {
        $("c_charge").val('');
    }, 500);
    return data;
}

// update salary data
function updateSalary() {
    let data = {
        "salary": $("#sa_salary").val()
    };
    setTimeout(() => {
        $("sa_salary").val('');
    }, 500);
    return data;
}